import os

from django.db import models

from User import Constants
from sportsground.utils.baseModels import BaseModels, IntegerChoices


class User(BaseModels):
    class Meta():
        db_table = 'user'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    class Sexs(IntegerChoices):
        Male = 1, "男"
        Female = 2, "女"
        Unkown = 3, "保密"

    # 个人信息
    nickname = models.CharField(null=True, max_length=20, verbose_name="昵称")
    phone = models.IntegerField(null=True, verbose_name="手机号")
    sex = models.IntegerField(choices=Sexs.choices, default=Sexs.Unkown, verbose_name="性别")
    birthday = models.DateField(null=True, verbose_name="生日")
    tall = models.IntegerField(null=True, verbose_name="身高")
    weight = models.IntegerField(null=True, verbose_name="体重")

    # 交易信息
    balance = models.FloatField(default=0, verbose_name="余额")
    shopCars = models.JSONField(default=list, verbose_name="购物车")

    @classmethod
    def create(cls):
        """ 创建用户 """
        user = cls(balance=10000)
        user.save()
        return user

    def Info(self):
        """ 个人信息 """
        return {
            "username": self.account_set.filter(user=self.id).first().username,
            "nickname": self.nickname,
            "phone": self.phone,
            "sex": self.sex,
            "birthday": self.birthday,
            "tall": self.tall,
            "weight": self.weight,
            "balance": self.balance,
            "shopCars": self.shopCars,
            "vips": self.uservip_set.filter(state=1).count(),
            "coupons": self.usercoupon_set.filter(state=1).count()
        }

    def getImage(self):
        """ 获取图片 """
        path = os.path.join(Constants.User_Image_Path, str(self.id))
        if os.path.exists(path):
            return open(path, 'rb')

    def saveImage(self, image):
        """ 保存图片 """
        path = os.path.join(Constants.User_Image_Path, str(self.id))
        with open(path, "wb") as f:
            f.write(image.read())

    def addShopCar(self, id, type,number):
        """ 添加购物车 """
        add = True
        shopCar = self.shopCars
        for i in range(len(shopCar)):
            shop = shopCar[i]
            if shop['type'] == type and shop['id'] == id:
                add = False
                shop['number'] = number
                shopCar[i] = shop
                break
        if add:
            shopCar.insert(0,{
                "id": id,
                "type": type,
                "number": number
            })
        self.shopCars = shopCar
        self.save()

    def popShopCar(self, id, type):
        """ 删除购物车 """
        shopCar = self.shopCars
        for i in range(len(shopCar)):
            shop = shopCar[i]
            if shop['type'] == type and shop['id'] == id:
                res = shopCar[i]
                del shopCar[i]
                self.shopCars = shopCar
                self.save()
                return res

    def consume(self, money):
        """ 消费 """
        self.balance -= money
        self.save()

    def income(self, money):
        """ 收入 """
        self.balance += money
        self.save()
